<template>
  <view class="personal safety-120">
    <mt-navbar title="个人信息" border-color="#dadbde"></mt-navbar>
    <block v-for="(item, index) in list" :key="index">
      <view
        v-if="item.isShow"
        :class="{
          'list': true,
          'px-24rpx': true,
          'py-36rpx': true,
          'flex': true,
          'justify-between': true,
          'items-center': true,
          'mb-18rpx': index === 0 || index === list.length - 1,
          'mt-18rpx': index === 0 || index === list.length - 1
        }"
        @click="handleClick(item)"
      >
        <view class="left text-#727687 text-28rpx">{{ item.label }}</view>
        <view class="right flex-1 flex justify-end items-center text-#1C213E text-28rpx">
          <view v-if="item.isShowRight" class="flex-1">
            <view v-if="item.key === 'avatarUrl'" class="flex justify-end">
              <mt-image-upload
                v-model="fileList"
                limit="1"
                replace
                :show-delete="false"
                width="104rpx"
                height="104rpx"
                @upload-change="handleChangeInfo('avatar')"
              >
              </mt-image-upload>
              <uv-icon name="arrow-right" class="pl-10rpx" color="#1C213E" size="18"></uv-icon>
            </view>

            <view v-else-if="item.key === 'city'" class="w-full flex">
              <view class="flex flex-1 justify-end items-center" @click="goSearchAddress">
                <view v-if="user.userInfo.registerZone > 0" class="tips-title text-28rpx">
                  {{ updateCityData.province }}-{{ updateCityData.city }}</view
                >
                <view v-else class="tips-title text-28rpx">更新位置</view>
                <uv-icon name="arrow-right" class="pl-24rpx" color="#1C213E" size="18"></uv-icon>
              </view>
            </view>
            <view v-else-if="item.key === 'wechat'" class="w-full flex">
              <view class="flex flex-1 justify-end items-center" @click="handleWechat">
                <view class="text-28rpx text-#1484EE"> {{ user.userInfo.bindWechat === 0 ? '绑定' : '解绑' }}</view>
              </view>
            </view>
            <view v-else class="text-align-right pr-24rpx ellipsis w-full">{{ item.value }}</view>
          </view>
          <uv-icon v-show="item.key !== 'city' && item.key !== 'avatarUrl'" name="arrow-right" color="#1C213E" size="18"></uv-icon>
        </view>
      </view>
    </block>

    <!--版本信息-->
    <view v-if="appVersion" class="flex flex-items-center flex-justify-around py-32rpx">
      <text class="text-#727687 fw-400 text-28rpx">版本号：{{ appVersion }}</text>
    </view>
    <view class="flex flex-items-center flex-justify-around pb-32rpx">
      <text class="text-#727687 fw-400 text-28rpx">Copyright © 2024 - 2025 易盟 iyimeng.com 版权所有</text>
    </view>
    <view class="flex flex-items-center flex-justify-around pb-32rpx">
      <text class="text-#727687 fw-400 text-28rpx">粤ICP备2025367460号-3A</text>
    </view>

    <view class="flex items-center justify-between px-32rpx fixed h-116rpx left-0 right-0 bottom-0 bg-#f7f7f7 safety-2">
      <mt-button :shake="false" class="w-100%" style="border-radius: 192rpx; background-color: #f94b4a" @click="handleLogOut">退出登录</mt-button>
    </view>

    <!--退出提示-->
    <mt-modal ref="mtModalLogoutRef">
      <view class="flex flex-justify-center py-24rpx">确认退出系统吗？</view>
    </mt-modal>
    <!--  -->
    <uv-popup ref="popupRef" round="16rpx" mode="bottom" z-index="900">
      <view class="px-32rpx py-60rpx">
        <view class="text-28rpx text-#727687 mb-24rpx">点击可复制或拨打电话</view>
        <view class="text-32rpx text-#1C213E mb-24rpx" @click="copyEmail">邮箱：info@iyimeng.com</view>
        <view class="text-32rpx text-#1C213E" @click="phoneCall">客服：400-900-8040</view>
      </view>
    </uv-popup>
  </view>
</template>

<script name="personal" setup>
import { logout, providerbindWechat, providerunbindWechat } from '@/api/login.js';
import userStore from '@/store/user';
import { updateProviderInfo, getProvinceInfo } from '@/api/index.js';
import { getFileName } from '@/utils/tools';

const user = userStore();

const mtModalLogoutRef = ref(null);

const registerZone = ref('');

const updateCityData = ref({});

const appVersion = ref(null);

// 头像
const fileList = ref([]);

const list = ref([
  {
    label: '我的头像',
    value: '',
    key: 'avatarUrl',
    isShowRight: true,
    isShow: true
  },
  {
    label: '我的名称',
    value: '',
    key: 'providerName',
    isShowRight: true,
    isShow: true
  },
  {
    label: '手机号',
    value: '',
    key: 'phone',
    isShowRight: true,
    isShow: true
  },
  {
    label: '微信',
    value: '',
    key: 'wechat',
    isShowRight: true,
    isShow: true
  },
  {
    label: '密码',
    value: '',
    key: 'password',
    isShowRight: false,
    isShow: true
  },
  {
    label: '注册地区',
    value: '',
    key: 'city',
    isShowRight: true,
    isShow: true
  },
  {
    label: '隐私政策',
    value: '',
    key: 'privacy',
    isShowRight: false,
    isShow: true
  },
  {
    label: '用户协议',
    value: '',
    key: 'user',
    isShowRight: false,
    isShow: true
  },
  {
    label: '反馈',
    value: '',
    key: 'feedback',
    isShowRight: false,
    isShow: true
  },
  {
    label: '注销账号',
    value: '',
    key: 'logoff',
    isShowRight: false,
    isShow: true
  }
]);

if (user.userInfo.pdWarning === 1) {
  list.value[4].label = '设置密码';
} else {
  list.value[4].label = '修改密码';
}

const popupRef = ref();

function openPopup() {
  popupRef.value.open();
}

function closePopup() {
  popupRef.value.close();
}

function copyEmail() {
  uni.setClipboardData({
    data: 'info@iyimeng.com',
    success: () => {
      uni.showToast({
        icon: 'none',
        title: '复制成功'
      });
      closePopup();
    }
  });
}

function phoneCall() {
  uni.makePhoneCall({
    phoneNumber: '4009008040',
    success: () => {
      closePopup();
    }
  });
}

// 点击对应的功能
const handleClick = (item) => {
  switch (item.key) {
    case 'password':
      uni.navigateTo({
        url: '/pages/index/changePassword?pdWarning=' + user.userInfo.pdWarning
      });
      break;
    case 'phone':
      uni.navigateTo({
        url: `/pages/index/changePhone?phone=${item.value}`
      });
      break;
    case 'providerName':
      uni.navigateTo({
        url: `/pages/index/changeUserName?providerName=${item.value}`
      });
      break;
    case 'privacy':
      uni.navigateTo({
        url: '/pages/common/webview?type=1'
      });
      break;
    case 'user':
      uni.navigateTo({
        url: '/pages/common/webview?type=2'
      });
      break;
    case 'feedback':
      openPopup();
      break;
    case 'logoff':
      uni.navigateTo({
        url: '/pages/login/bindAccount?type=6'
      });
      break;
    default:
      break;
  }
};

// 修改地区
const handleChangeInfo = async (type) => {
  const params = {
    avatarUrl: type === 'avatar' ? fileList.value[0]?.url : user.userInfo.avatarUrl,
    providerName: user.userInfo.providerName ? user.userInfo.providerName : null,
    registerZone: type === 'city' ? registerZone.value : user.userInfo.registerZone
  };
  await updateProviderInfo(params);
  uni.showToast({
    title: '修改成功',
    icon: 'none'
  });
};

// 退出登录
const handleLogOut = async () => {
  const options = {
    cancelText: '取消',
    confirmText: '确认退出',
    slot: true,
    title: '系统提示',
    success: async (e) => {
      if (e.confirm) {
        await logout();
        uni.reLaunch({
          url: '/pages/login/phoneQuick'
        });
        uni.showToast({
          title: '退出成功',
          icon: 'none'
        });
      }
    }
  };
  mtModalLogoutRef.value.open(options);
};

// 处理头像长度
const formatAvatar = (avatarUrl) => {
  if (!avatarUrl.url) return '';
  const reg = /\/([^\/]+)(\.[^\/]+)$/;
  let fileName = avatarUrl.url.match(reg)[1];
  let newFilePath = avatarUrl.url.replace(fileName, 'avatar');
  return newFilePath;
};

// 注册地区修改
function goSearchAddress() {
  uni.setStorageSync('selectCity', {
    provinceCode: user.userInfo.registerZone ? user.userInfo.registerZone.toString().substring(0, 2) + '0000' : '',
    province: user.userInfo.registerProvinceName,
    cityCode: user.userInfo.registerZone,
    city: user.userInfo.registerCityName
  });
  uni.navigateTo({
    url: '/pages/common/selectCity'
  });
  // if (user.userInfo.registerZone > 0) {
  //   uni.setStorageSync('selectCity', {
  //     provinceCode: user.userInfo.registerZone ? user.userInfo.registerZone.toString().substring(0, 2) + '0000' : '',
  //     province: user.userInfo.registerProvinceName,
  //     cityCode: user.userInfo.registerZone,
  //     city: user.userInfo.registerCityName
  //   });
  //   uni.navigateTo({
  //     url: '/pages/common/selectCity'
  //   });
  // } else {
  //   getLocation();
  // }
}

async function handleWechat() {
  if (user.userInfo.bindWechat === 0) {
    uni.login({
      provider: 'weixin',
      onlyAuthorize: true,
      success: (event) => {
        // 获取微信code
        const { code } = event;
        providerbindWechat({
          code
        }).then(() => {
          uni.showToast({
            title: '绑定成功',
            icon: 'none'
          });
          user.setUserInfo({
            ...user.userInfo,
            bindWechat: 1
          });
        });
      },
      fail: (err) => {}
    });
  } else {
    await providerunbindWechat();
    uni.showToast({
      title: '解绑成功',
      icon: 'none'
    });
    user.setUserInfo({
      ...user.userInfo,
      bindWechat: 0
    });
  }
}

// 监听城市变化并修改
uni.$on('getSelectCityData', async (item) => {
  registerZone.value = item.cityCode;
  handleChangeInfo('city');
  updateCityData.value = item;
  user.setUserInfo({
    ...user.userInfo,
    registerZone: item.cityCode.toString(),
    registerProvinceName: item.province,
    registerCityName: item.city
  });
});

async function getUserInfo() {
  const res = await getProvinceInfo();
  user.setUserInfo(res.data);
}

async function getLocation() {
  try {
    const res = await uni.getLocation({
      type: 'gcj02'
    });
    const amapRes = await uni.request({
      url: 'https://restapi.amap.com/v3/geocode/regeo',
      data: {
        key: 'c84e8a3eb2ff126b055bf0278bc7caa9',
        location: `${res.longitude},${res.latitude}`
      }
    });
    const adcode = amapRes.data.regeocode.addressComponent.adcode;
    const citycode = adcode.slice(0, 4) + '00';

    await updateProviderInfo({
      registerZone: citycode
    });

    await getUserInfo();
    uni.showToast({
      icon: 'none',
      title: '地址信息完善成功'
    });
    init();
  } catch (error) {}
}

function init() {
  updateCityData.value.province = user.userInfo.registerProvinceName;
  updateCityData.value.city = user.userInfo.registerCityName;
  list.value.forEach((item) => {
    if (item.key === 'city') {
      item.value = `${user.userInfo['registerProvinceName']}-${user.userInfo['registerCityName']}`;
    } else {
      item.value = user.userInfo[item.key];
    }
  });
  registerZone.value = user.userInfo.registerZone.toString();
}

onLoad(() => {
  const systemInfo = uni.getSystemInfoSync();
  appVersion.value = systemInfo.appVersion;
});

onUnload(() => {
  // 移除监听事件 优化性能
  uni.$off('getSelectCityData');
});

onShow(() => {
  const name = getFileName(user.userInfo.avatarUrl);
  fileList.value = [{ name: name, url: user.userInfo.avatarUrl }];
  list.value.forEach((item) => {
    if (item.key === 'city') {
      item.value = `${user.userInfo['registerProvinceName']}-${user.userInfo['registerCityName']}`;
    } else {
      item.value = user.userInfo[item.key];
    }
  });
  if (user.userInfo.registerZone > 0) {
    init();
  }
});
</script>

<style lang="scss" scoped>
.personal {
  background-color: #f7f7f7;
  min-height: 100vh;
  :deep(.mt-image-upload) {
    padding-top: 10rpx;
    .image-box {
      margin-right: 0;
      margin-bottom: 0;
      background-color: #ffffff;
      border-radius: 100%;
      border: 1px solid #fff;
      .img {
        border-radius: 100%;
      }
    }
  }
  .list {
    border-bottom: 0.5px solid #eaeaea;
    background-color: #ffffff;
  }

  .log-out {
    box-sizing: border-box;
    position: fixed;
    bottom: 50rpx;
    padding: 24rpx;
  }
}
</style>
